#!/usr/bin/env python
# -*-coding:utf-8 -*-
__author__ = 'whisky'
__date__ = '2018/12/25 15:01'

from users.models import EmailVerifyRecord
from random import Random
from django.core.mail import send_mail
from MxOnline.settings import EMAIL_FROM

def random_str(randomlength=8):
    """生成随机数"""
    str = ''
    chars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    random = Random()
    length = len(chars) - 1
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str


def send_register_email(email, send_type='register'):
    """
    发送邮件并记录入库
    :param email:
    :param send_type:
    :return:
    """
    eamil_record = EmailVerifyRecord()
    if send_type == "update_email":
        code = random_str(4)
    else:
        code = random_str(16)
    eamil_record.code = code
    eamil_record.email = email
    eamil_record.send_type = send_type
    eamil_record.save()

    email_title = ""
    email_body = ""
    if send_type == 'register':
        email_title = 'whisky在线激活链接'
        email_body = '请点击下面的链接激活你的账户:http://127.0.0.1:8000/active/{0}'.format(code)

        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass

    elif send_type == 'forget':
        email_title = 'whisky在线密码重置连接'
        email_body = '请点击下面的链接激活你的密码:http://127.0.0.1:8000/reset/{0}'.format(code)

        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass

    elif send_type == 'update_email':
        email_title = 'whisky在线邮箱修改验证码'
        email_body = '你的邮箱验证码为：{0}'.format(code)

        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass